#include "tasklist.h"
#include <QVBoxLayout>
#include <QDebug>

#include "ukuiwindow.h"
#include "ukuitaskbarpreviewwidget.h"
#include "commonutil.h"

TaskList::TaskList(QWidget *parent)
{
}

TaskList::~TaskList()
{
    if(m_layout!=nullptr) {
        delete m_layout;
        m_layout = nullptr;
    }
}

void TaskList::setData(QMap<UKUIWindow *, UKUITaskbarPreviewWidget *> &mapWindowPreview)
{
    m_mapWindowPreview = &mapWindowPreview;

    connect(&mCloseTimer, &QTimer::timeout, this, &TaskList::closeTimerSlot);
    mCloseTimer.setSingleShot(true);
    //mCloseTimer.setInterval(400);
    mCloseTimer.setInterval(900);

    initUI();
}

void TaskList::hide(bool fast)
{
    if (fast)
        close();
    else
        mCloseTimer.start();
}

void TaskList::enterEvent(QEvent *event)
{
    //??why need a timer?
    QTimer::singleShot(CommonUtil::getPopWindowDelayTime(), this, [=](){
        if(mCloseTimer.isActive())
        {
            mCloseTimer.stop();
        }
    });
}

void TaskList::leaveEvent(QEvent *event)
{
    QTimer::singleShot(CommonUtil::getPopWindowDelayTime(), this, [=](){
        if(mCloseTimer.isActive())
        {
            mCloseTimer.stop();
        }
        close();
    });
}

void TaskList::dataChanged()
{
    //add new window or delete window

    //remove old stuff
    delete m_layout;
    m_layout = nullptr;

    initUI();
}

void TaskList::closeTimerSlot()
{
    close();
}

void TaskList::initUI()
{
    setWindowFlags(Qt::FramelessWindowHint | Qt::ToolTip);
    setAttribute(Qt::WA_AlwaysShowToolTips);
    setAttribute(Qt::WA_TranslucentBackground);

    m_layout = new QVBoxLayout();
    m_layout->setAlignment(Qt::AlignTop);
    m_layout->setSpacing(3);
    m_layout->setMargin(3);

    foreach(UKUIWindow* window, m_mapWindowPreview->keys()) {
        UKUITaskbarPreviewWidget* widget = m_mapWindowPreview->value(window);
        qDebug()<<window->getAppName();
        widget->setPreviewVisible(false);
        m_layout->addWidget(widget);
    }

    setLayout(m_layout);
}
